﻿Public Class frmGLGeneralLedgerEntry
    Dim dbSystem As New dbSystem
    Dim dbGL As New dbGL
    Dim Var As New varDeclare
    Dim frmCtrl As New FormControl
    Dim curr2word As New Currency
    Dim dsBase As DataSet
    Dim dsGLAccount As DataSet
    Dim dsCurr As DataSet
    Dim TotalDebet As Decimal
    Dim TotalCredit As Decimal
    Dim CurrBase As String
    Public EntryID As String
    Dim dgvTemp As New DataGridView

    Public Class Sample
        Public Property Satus As Boolean
        Public Property Name As String
        Public Property ID As Integer
    End Class

    Private Sub frmEntryGL_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        dsCurr = dbSystem.CurrList(Var.CompID)
        If (dsCurr.Tables(0).Rows.Count > 0) Then
            For i = 0 To dsCurr.Tables(0).Rows.Count - 1
                Try
                    cbJournalCurr.Items.Add(dsCurr.Tables(0).Rows(i)("ID").ToString().Trim())
                Catch ex As Exception
                End Try
            Next
        End If
        txtJournalID.Text = EntryID
        dsBase = dbGL.GLJournalDetail(Var.CompID, txtJournalID.Text.Trim())
        dgvTemp.Columns.Add("clID", "clID")
        dgvTemp.Rows.Add(EntryID)
        ToolbarHeader1.DefaultRow = 1
        ToolbarHeader1.Iniliaze("Entry : General Ledger", Me, New frmGLGeneralLedger, dgvTemp, "clID")
        If (dsBase.Tables(1).Rows.Count() > 0) Then
            dgvBase.Rows.Add(dsBase.Tables(1).Rows.Count)
            For i = 0 To dsBase.Tables(1).Rows.Count - 1
                Try
                    dgvBase.Rows(i).Cells("clNr").Value = dsBase.Tables(1).Rows(i)("Nr").ToString().Trim()
                    dgvBase.Rows(i).Cells("clGLAccount").Value = dsBase.Tables(1).Rows(i)("GL Account").ToString().Trim()
                    dgvBase.Rows(i).Cells("clGLName").Value = dsBase.Tables(1).Rows(i)("GL Account Name").ToString().Trim()
                    dgvBase.Rows(i).Cells("clNotes").Value = dsBase.Tables(1).Rows(i)("Notes").ToString().Trim()
                    dgvBase.Rows(i).Cells("clDebet").Value = Convert.ToDecimal(dsBase.Tables(1).Rows(i)("Debet")).ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
                    dgvBase.Rows(i).Cells("clCredit").Value = Convert.ToDecimal(dsBase.Tables(1).Rows(i)("Credit")).ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
                Catch ex As Exception
                End Try
            Next
            Toolbar(True, True, True, True, False, False, True, True)
            If (EntryID = "") Then
                Toolbar(False, False, False, False, False, False, False, True)
            End If
        End If
        If (dsBase.Tables(0).Rows.Count() > 0) Then
            txtJournalNotes.Text = dsBase.Tables(0).Rows(0)("Notes").ToString().Trim()
            CurrBase = dsBase.Tables(0).Rows(0)("CurrBase").ToString().Trim()
            txtJournalRate.Text = Convert.ToDecimal(dsBase.Tables(0).Rows(0)("CurrRate").ToString().Trim()).ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
            cbJournalCurr.Text = dsBase.Tables(0).Rows(0)("CurrID").ToString().Trim()
            dtJournalDate.Value = Convert.ToDateTime(dsBase.Tables(0).Rows(0)("JournalDate"))
        End If
        UpdateBalance()
    End Sub

    ''================================== Control Header ==============================================''
    Private Sub tsNew_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsNewClick
        Dim OpenForm As New frmGLGeneralLedgerEntry
        OpenForm.EntryID = ""
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsEdit_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsEditClick
        Toolbar(False, False, False, False, True, True, False, True)
        dgvBase.ReadOnly = False
        gbForm.Enabled = True
        dgvBase.ContextMenuStrip = cmsGL
        UpdateBalance()
    End Sub

    Private Sub tsDelete_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsDeleteClick
        If (EntryID.Trim() <> "") Then
            Dim result As Boolean = dbGL.deleteJournalGL(txtJournalID.Text, Var.CompID)
            frmCtrl.openChild(New frmGLGeneralLedger, Me.ParentForm)
        Else : MessageBox.Show("Please Choose GL First")
        End If
    End Sub

    Private Sub tsSave_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsSaveClick
        Dim x As Array = txtJournalID.Text.Split("-")
        EntryID = dbGL.SaveJournalHeaderGL(EntryID, _
                                             txtJournalID.Text, _
                                             x(0).ToString(), _
                                             dtJournalDate.Value.ToString("yyyy"), _
                                             dtJournalDate.Value, _
                                             txtJournalNotes.Text.Trim(), _
                                             cbJournalCurr.Text, _
                                             Convert.ToDecimal(txtJournalRate.Text), _
                                             CurrBase, _
                                             TotalDebet, _
                                             TotalCredit, _
                                             MDI.LoginID, _
                                             Var.CompID)
        Dim Seq As Integer
        Dim status As Boolean = True
        For i = 0 To dgvBase.Rows.Count - 2
            If (status) Then
                If (dgvBase.Rows(i).Cells("clGLName").Value.ToString() <> "") Then
                    Seq = Convert.ToInt32(dgvBase.Rows(i).Cells("clNr").Value)
                    Dim Notes As String = ""
                    If (dgvBase.Rows(i).Cells("clNotes").Value Is Nothing) Then
                        Notes = ""
                    Else
                        Notes = dgvBase.Rows(i).Cells("clNotes").Value.ToString()
                    End If
                    Dim vDebet As Decimal = Convert.ToDecimal(dgvBase.Rows(i).Cells("clDebet").Value) * Convert.ToDecimal(txtJournalRate.Text)
                    Dim vCredit As Decimal = Convert.ToDecimal(dgvBase.Rows(i).Cells("clCredit").Value) * Convert.ToDecimal(txtJournalRate.Text)
                    status = dbGL.SaveJournalLineGL(EntryID, _
                                                    dtJournalDate.Value, _
                                                    Seq, _
                                                    dgvBase.Rows(i).Cells("clGLAccount").Value.ToString(), _
                                                    Notes, _
                                                    dgvBase.Rows(i).Cells("clDebet").Value.ToString(), _
                                                    dgvBase.Rows(i).Cells("clCredit").Value.ToString(), _
                                                    cbJournalCurr.Text, _
                                                    Convert.ToDecimal(txtJournalRate.Text), _
                                                    "", _
                                                    Var.CompID)

                End If
            End If
        Next
        If (status) Then
            frmCtrl.openChild(frmGLGeneralLedger, Me.ParentForm)
        Else
            MessageBox.Show("Saving GL " + EntryID + " , Failed at Seq" + Seq.ToString())
        End If
    End Sub

    Private Sub tsPrint_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsPrintClick
        Dim journalCode As Array = EntryID.Split("-")
        Dim JournalNo As Array = journalCode(1).ToString().Split("/")
        Dim dsReport As DataSet = New dbReport().GenerateJournalReport(journalCode(0).ToString().Trim(), JournalNo(1).ToString().Trim(), "", JournalNo(0).ToString().Trim(), JournalNo(0).ToString().Trim())
        If (dsReport IsNot Nothing) Then
            Dim frmViewReport As New ViewReport
            frmViewReport.strReport = "Journal"
            frmViewReport.dsReport = dsReport
            frmViewReport.Show()
        End If
    End Sub

    Private Sub tsRefresh_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsRefreshClick
        Dim OpenForm As New frmGLGeneralLedgerEntry
        OpenForm.EntryID = EntryID
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsCancel_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsCancelClick
        Dim OpenForm As New frmGLGeneralLedgerEntry
        OpenForm.EntryID = EntryID
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub
    ''================================== Control Header [End] ==============================================''

    Private Sub dgvBase_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles dgvBase.RowsAdded
        dgvBase.Item(0, dgvBase.Rows.Count - 1).Value = dgvBase.Rows.Count
    End Sub

    Private Sub dgvBase_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBase.CellValueChanged
        UpdateBalance()
    End Sub

    Private Sub UpdateBalance()
        Dim balance As Decimal = 0
        TotalDebet = 0
        TotalCredit = 0
        Dim Debet As Decimal = 0
        Dim Credit As Decimal = 0
        If (txtJournalID.Text <> "" And cbJournalCurr.Text <> "" And txtJournalRate.Text <> "") Then
            For i = 0 To dgvBase.Rows.Count - 1
                Try
                    If (dgvBase.Rows(i).Cells("clDebet").Value = "" Or IsNumeric(dgvBase.Rows(i).Cells("clDebet").Value) = False) Then
                        dgvBase.Rows(i).Cells("clDebet").Value = "0"
                    End If
                    If (dgvBase.Rows(i).Cells("clCredit").Value = "" Or IsNumeric(dgvBase.Rows(i).Cells("clCredit").Value) = False) Then
                        dgvBase.Rows(i).Cells("clCredit").Value = "0"
                    End If
                    If (Convert.ToDecimal(dgvBase.Rows(i).Cells("clDebet").Value) < 0) Then
                        MessageBox.Show("Amount can't minus")
                        dgvBase.Rows(i).Cells("clDebet").Value = "0"
                    End If
                    If (Convert.ToDecimal(dgvBase.Rows(i).Cells("clCredit").Value) < 0) Then
                        MessageBox.Show("Amount can't minus")
                        dgvBase.Rows(i).Cells("clCredit").Value = "0"
                    End If
                    If (dgvBase.Rows(i).Cells("clGLAccount").Value.ToString() <> "") Then
                        Dim debetValue As Decimal = Convert.ToDecimal(dgvBase.Rows(i).Cells("clDebet").Value)
                        Dim creditValue As Decimal = Convert.ToDecimal(dgvBase.Rows(i).Cells("clCredit").Value)
                        If (debetValue > 0) Then
                            creditValue = 0
                        End If
                        dgvBase.Rows(i).Cells("clDebet").Value = debetValue.ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
                        dgvBase.Rows(i).Cells("clCredit").Value = creditValue.ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
                        Debet += debetValue
                        Credit += creditValue
                    End If
                    If (i = dgvBase.Rows.Count - 1) Then
                        dgvBase.Rows.Add(1)
                        If (dgvBase.ReadOnly = False) Then
                            Toolbar(False, False, False, False, True, True, False, True)
                            dgvBase.ReadOnly = False
                            gbForm.Enabled = True
                            dgvBase.ContextMenuStrip = cmsGL
                        End If
                    End If
                Catch ex As Exception
                End Try
            Next
        End If
        balance = Debet - Credit
        ToolbarBalance1.CheckBalance(Debet, Credit)
        ToolbarHeader1.tsSave.Enabled = (Debet > 0)
        If (balance <> 0) Then
            ToolbarHeader1.tsSave.Enabled = False
        End If
        TotalCredit = Credit
        TotalDebet = Debet
    End Sub

    <System.Diagnostics.DebuggerStepThrough()> _
    Function IsHeaderButtonCell(ByVal GridView As DataGridView, ByVal e As DataGridViewCellEventArgs) As Boolean
        Return TypeOf GridView.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso Not e.RowIndex = -1
    End Function

    Private Sub dgvBase_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBase.CellClick
        If (gbForm.Enabled And txtJournalID.Text <> "" And cbJournalCurr.Text <> "" And txtJournalRate.Text <> "") Then
            If (IsHeaderButtonCell(dgvBase, e)) Then
                Dim formFind As New frmFind
                formFind.lblTitle.Text = "Search : Chart of Account "
                formFind.QueryHeader = "SELECT GLAC_CODE 'GL Account ID',GLAC_DESC 'GL Account Name' From GL_ACCOUNT WITH(NOLOCK) WHERE COMP_CODE = " + Var.CompID
                formFind.StartPosition = FormStartPosition.CenterScreen
                formFind.type = "cell"
                formFind.dgCellValue1 = dgvBase.Rows(e.RowIndex).Cells("clGLAccount")
                formFind.dgCellValue2 = dgvBase.Rows(e.RowIndex).Cells("clGLName")
                formFind.Show()
                MDI.Enabled = False
            End If
        End If
    End Sub

    Private Sub Toolbar(N As Boolean, E As Boolean, D As Boolean, P As Boolean, S As Boolean, C As Boolean, R As Boolean, X As Boolean)
        ToolbarHeader1.ActionCtrl(N, False, E, D, P, S, C, R, X)
        If (EntryID <> "") Then
            dgvBase.ReadOnly = True
            gbForm.Enabled = False
            dgvBase.ContextMenuStrip = Nothing
        End If
    End Sub

    Private Sub tsExit_Click(sender As Object, e As EventArgs)
        frmCtrl.openChild(frmGLGeneralLedger, Me.ParentForm)
    End Sub

    Private Sub btnEditJournalID_Click(sender As Object, e As EventArgs) Handles btnEditJournalID.Click
        If (EntryID = "") Then
            Dim formFind As New frmFind
            formFind.lblTitle.Text = "Search : GL Journal Group"
            formFind.QueryHeader = "SELECT GLTR_JURNAL_CODE 'GLJournalID',GLTR_JURN_DESC 'GLJournalName' From GL_TRANS_HEADER WITH(NOLOCK) WHERE GLTR_COMP_CODE = " + Var.CompID
            formFind.StartPosition = FormStartPosition.CenterScreen
            formFind.type = "txt"
            formFind.txtValue = txtJournalID
            formFind.Show()
            MDI.Enabled = False
        End If
    End Sub

    Private Sub txtJournalID_TextChanged(sender As Object, e As EventArgs) Handles txtJournalID.TextChanged
        If (txtJournalID.Text <> "" And txtJournalID.Text.Trim().Length < 5) Then
            Dim x As Array = txtJournalID.Text.Split("-")
            Dim Type As String = x(0).ToString()
            Dim Periode As String = dtJournalDate.Value.ToString("yyyy")
            Dim Seq As String = dbGL.getSeqJournalID(Type, Periode)
            txtJournalID.Text = Type + "-" + Seq + "/" + Periode
        End If
    End Sub

    Private Sub dtJournalDate_ValueChanged(sender As Object, e As EventArgs) Handles dtJournalDate.ValueChanged
        If (txtJournalID.Text <> "") Then
            Dim x As Array = txtJournalID.Text.Split("/")
            Dim Periode As String = dtJournalDate.Value.ToString("yyyy")
            txtJournalID.Text = x(0).ToString() + "/" + Periode
        End If
    End Sub

    Private Sub txtJournalRate_Leave(sender As Object, e As EventArgs) Handles txtJournalRate.Leave
        If (txtJournalRate.Text = "" Or IsNumeric(txtJournalRate.Text.Trim()) = False) Then
            txtJournalRate.Text = "0"
        End If
        txtJournalRate.Text = Convert.ToDecimal(txtJournalRate.Text).ToString("N2", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
    End Sub

    Private Sub cbJournalCurr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbJournalCurr.SelectedIndexChanged
        If (cbJournalCurr.SelectedItem.ToString() <> "") Then
            Dim dvCurr As DataView = New DataView(dsCurr.Tables(0))
            dvCurr.RowFilter = "[ID] = '" & cbJournalCurr.SelectedItem.ToString() & "'"
            CurrBase = dvCurr.Item(0).Row("CurrBase").ToString()
            If (Convert.ToDecimal(txtJournalRate.Text) = 0) Then
                txtJournalRate.Text = dvCurr.Item(0).Row("CurrRate").ToString()
            End If
        End If
    End Sub

    Private Sub DeleteRowToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteRowToolStripMenuItem.Click
        Dim rowCount As Integer = dgvBase.RowCount
        If (rowCount > 1) Then
            Dim rowI As Integer = dgvBase.CurrentRow.Index
            dgvBase.Rows.RemoveAt(rowI)
            For i = 0 To rowCount - 2
                dgvBase.Item(0, i).Value = i + 1
            Next
        End If
    End Sub

    Private Sub dgvBase_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvBase.CellMouseDown
        If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex >= 0 Then
            dgvBase.ClearSelection()
            dgvBase.CurrentCell = dgvBase.Rows(e.RowIndex).Cells(0)
            dgvBase.Rows(e.RowIndex).Selected = True
        End If
    End Sub
End Class